package com.flca.dbs.jpa;

import javax.persistence.EntityManager;

import com.flca.frw.dao.Dao;
import com.flca.frw.dao.PersistenceType;

public class JpaDaoImpl implements Dao {

	private static final long serialVersionUID = 6859145331274345649L;

	private EntityManager em;

	public JpaDaoImpl() {
	}

	public JpaDaoImpl(EntityManager aEntityManager) {
		em = aEntityManager;
	}
	
	@Override
	public Object getObjectMgr() {
		return em;
	}

	@Override
	public boolean isInTransaction() throws Exception  {
		if (em != null && em.getTransaction() != null) {
			return em.getTransaction().isActive();
		}
		return false;
	}

	@Override
	public void commit() throws Exception {
		if (em != null && em.isOpen() && em.getTransaction() != null && em.getTransaction().isActive()) {
			em.getTransaction().commit();
		} else {
			logError("commit called with EntityManager null");
		}
	}

	@Override
	public void rollback() throws Exception {
		if (em != null && em.getTransaction() != null) {
			em.getTransaction().rollback();
		} else {
			logError("rollback called with EntityManager null");
		}
	}

	@Override
	public void startTransaction() throws Exception {
		if (em != null && em.getTransaction() != null) {
			em.getTransaction().begin();
		} else {
			throw new NullPointerException("startTransaction called with EntityManager null");
		}
	}

	@Override
	public PersistenceType technology() {
		return PersistenceType.JPA; 
	}
	
	private void logError(String msg) {
		System.out.println(msg);
	}


}
